import classNames from 'classnames';
import { useContext, useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import Form from '../Form';
import FormInput from '../FormInput';
import { ThemeContext } from '../../context/ThemeContext';
// import { PageForm } from 'src/model/Form';
import style from './Pagination.module.scss';

type PageForm = any

type Props = {
  page: number;
  pageCount: number;
  setPage?: (v: number) => void;
};

const Pagination = ({ page, pageCount, setPage }: Props) => {
  const [error, setError] = useState<boolean>(false);
  const { IcPaginationNext, IcPaginationPrev } = useContext(ThemeContext).image;
  const methods = useForm<PageForm>();
  useEffect(() => {
    methods.setValue('page', page.toString());
  }, [page]);

  const isValidPage = (v: number) => v >= 1 && v <= pageCount;

  const onPageChange = (v: number) => {
    if (!isValidPage(v)) return;
    setPage && setPage(v);
  };

  const onSubmit = (data: PageForm) => {
    const inputPage = Number(data.page);
    if (isValidPage(inputPage)) {
      setError(false);
      setPage && setPage(inputPage);
    } else setError(true);
  };

  return (
    <div className={style.self}>
      <div className={style.img} onClick={() => onPageChange(page - 1)}>
        <img src={IcPaginationPrev} />
      </div>
      <Form methods={methods} onSubmit={onSubmit}>
        <FormInput
          name="page"
          defaultValue={page}
          className={classNames(style.input, { [style.error]: error })}
          regex={new RegExp('^\\d*$')}
        />
      </Form>
      <div>/</div>
      <div>{pageCount < 1 ? '-' : pageCount}</div>
      <div className={style.img} onClick={() => onPageChange(page + 1)}>
        <img src={IcPaginationNext} />
      </div>
    </div>
  );
};

export default Pagination;
